{extend name="layout/base" /}
{block name="title"}我的购物车 - {mall:config name="mall.sitename"/}{__block__}{/block}
{block name="meta"}
{__block__}
<link href="__ADDON__/__STYLE__/css/cart.css" rel="stylesheet">
<link href="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table.min.css" rel="stylesheet">
<link href="__ADDON__/__STYLE__/js/bt-ext/bt-group-by.css" rel="stylesheet">
<link rel="stylesheet" href="__CDN__/assets/libs/nice-validator/dist/jquery.validator.css">
<link rel="stylesheet" href="__CDN__/assets/libs/fastadmin-selectpage/selectpage.css">
{/block}

{block name="body"}
<body class="shopping_cart_page">
{/block}

{block name="main"}
<div class="container">
    <div id="stepflex" class="stepflex">
        <dl class="first doing">
            <dt class="s-num">1</dt>
            <dd class="s-text">我的购物车</dd>
            <dd></dd>
        </dl>
        <dl class="normal doing">
            <dt class="s-num">2</dt>
            <dd class="s-text">填写核对订单信息</dd>
        </dl>
        <dl class="last">
            <dt class="s-num1">3</dt>
            <dd class="s-text1">成功提交订单</dd>
        </dl>
    </div>
    <div class='mall-clear'></div>

    <div class='main-head'>填写并核对订单</div>
    <form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="/addons/mall/order/addVisitor">
        <!-- 送货方式 -->
        <div class='address-box'>
            <div class='box-head'>送货方式</div>
            <div class="mall-list-box">
                <div class="mall-frame2 j-selected" onclick="javascript:changeDeliverType(0,'deliverType',this)">
                    快递运输<i></i></div>
                <div class="mall-frame2" onclick="javascript:changeDeliverType(1,'deliverType',this)">自提<i></i></div>
                <input type='hidden' value='0' id='c-deliverType' name='row[deliverType]'/>
                <div class='mall-clear'></div>
            </div>
        </div>
        <!-- 用户地址 -->
        <div class='pay-box'>
            <div class='box-head'>收货人信息</div>
            <div class="form-group">
                <label class="control-label col-xs-12 col-sm-2">{:__('Username')}:</label>
                <div class="col-xs-12 col-sm-8">
                    <input id="c-userName" data-rule="required" class="form-control" name="row[userName]" type="text" value="">
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-xs-12 col-sm-2">{:__('Phone')}:</label>
                <div class="col-xs-12 col-sm-8">
                    <input id="c-userPhone" class="form-control" name="row[userPhone]" type="text">
                </div>
            </div>
            <div class="form-group address">
                <label class="control-label col-xs-12 col-sm-2">{:__('Area')}:</label>
                <div class="col-xs-12 col-sm-8">
                    <input id="c-area_ids" data-rule="required" class="form-control" name="row[area_ids]" type="hidden" value="0">
                    <div class="col-xs-3">
                        <input name="row[category1]" value="" data-params='{"custom[pid]":"0"}' id="c-category1"
                               data-source="/user/mall/oper/area/selectpage" class="form-control selectpage"
                               placeholder="{:__('Category L1')}" type="text">
                    </div>
                    <div class="col-xs-3">
                        <input name="row[category2]" value="" id="c-category2"
                               data-source="/user/mall/oper/area/selectpage" class="form-control selectpage"
                               placeholder="{:__('Category L2')}" type="text">
                    </div>
                    <div class="col-xs-3">
                        <input name="row[category3]" value="" id="c-category3"
                               data-source="/user/mall/oper/area/selectpage" class="form-control selectpage"
                               placeholder="{:__('Category L3')}" type="text">
                    </div>
                    <div class="col-xs-3">
                        <input name="row[category4]" value="" id="c-category4"
                               data-source="/user/mall/oper/area/selectpage" class="form-control selectpage"
                               placeholder="{:__('Category L4')}" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group address">
                <label class="control-label col-xs-12 col-sm-2">{:__('Useraddress')}:</label>
                <div class="col-xs-12 col-sm-8">
                    <input id="c-userAddress" data-rule="required" class="form-control" name="row[userAddress]" type="text" value="">
                </div>
            </div>
        </div>
        <!-- 支付方式 -->
        <div class='pay-box'>
            <div class='box-head'>支付方式</div>
            <div class="mall-list-box">
                <div class="mall-frame2 j-selected" onclick="javascript:changeSelected(0,'payType',this)">货到付款<i></i></div>
                <div class="mall-frame2" onclick="javascript:changeSelected(1,'payType',this)">在线支付<i></i>
                </div>
                <input type='hidden' value="0" id='c-payType' name='row[payType]'/>
                <div class='mall-clear'></div>
            </div>
        </div>
        <!-- 商品清单 -->
        <div class='cart-box2'>
            <div class='box-head2'>商品清单</div>
            <input type='hidden' value="{$num}" id='c-num' name='row[num]'/>
            <table id="table"
                   data-group-by="true"
                   data-group-by-field="name"
                   data-group-by-sum-field="shoptotal"
                   data-group-by-total-field="carttotal">
                <thead>
                <tr>
                    <th data-field="goodsimg" data-formatter="imageFormatter">图片</th>
                    <th data-field="goodsname" data-formatter="goodsnameFormatter">名称与规格</th>
                    <th data-field="shopprice" data-align="right" data-valign="middle">价格</th>
                    <th data-field="num" data-align="center" data-valign="middle">数量</th>
                    <th data-field="total" data-align="right" data-valign="middle">小计</th>
                </tr>
                </thead>
            </table>
            <div class='cart-footer'>
                <div class='cart-summary2'>
                    <!-- 发票信息 -->
                    <div class="pay-box">
                        <div class='box-head'>发票信息</div>
                        <div class="j-show-box">

                            <div style="float:left;" id="invoice_info">不开发票</div>
                            <div style="float:left;color:blue;margin-left:10px;cursor:pointer;"
                                 onclick='javascript:changeInvoice(1,"#invoiceClientDiv",this)'>修改
                            </div>

                            <div class="mall-clear"></div>
                            <input type="hidden" id="c-invoice_obj" name="row[invoice_obj]" value="0"/>
                            <input type="hidden" id="c-invoiceId" name="row[invoiceId]" value="0"/>
                            <input type='hidden' id='c-invoiceis' name="row[invoiceis]" value='0'/>
                            <input type='hidden' id='c-invoiceClient' name="row[invoiceClient]" value='个人'/>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class='cart-btn'>
            <a href='{:addon_url("mall/cart/indexVisitor")}' class='mall-prev mall-cart-asha' style='width:105px;height:33px;line-height:33px;'>上一步</a>
            <a href='javascript:void(0)' onclick='javascript:addOrder()' class='mall-order mall-cart-reda' style='width:118px;height:33px;line-height:33px;'>提交订单</a>
            <div class='mall-clear'></div>
        </div>
    </form>

</div>

{/block}

{block name="js"}
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<script src="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table.min.js"></script>
<script src="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table-locale-all.min.js"></script>
<script src="__ADDON__/__STYLE__/js/bt-ext/bt-group-by.js"></script>
<script>
    var num = {$num};

    var $table = $('#table')

    function initTable() {
        $table.bootstrapTable({
            locale: require.config.language,
            "url": "/addons/mall/order/getOrderMoney?num=" + num,
            "groupByFormatter": function (value, row, index) {
                var html = [];
                html.push(value);
                if (row['shopQQ'] != '') {
                    html.push('<a href="tencent://message/?uin=' + row['shopQQ'] + '&Site=QQ交谈&Menu=yes">\n' +
                        '<img border="0" src="https://wpa.qq.com/pa?p=1:' + row['shopQQ'] + ':7" alt="QQ交谈" width="71" height="24" />\n' +
                        '</a>\n');
                }
                if (row['shopWangWang'] != '') {
                    html.push('<a target="_blank" href="https://www.taobao.com/webww/ww.php?ver=3&touid=' + row['shopWangWang'] + '&siteid=cntaobao&status=1&charset=utf-8">\n' +
                        '<img border="0" src="https://amos.alicdn.com/realonline.aw?v=2&uid=' + row['shopWangWang'] + '&site=cntaobao&s=1&charset=utf-8" alt="和我联系" />\n' +
                        '</a>\n');
                }
                html.push('订单备注：<input type="text" id="c-orderRemarks" value="' + row.remark + '" name="row[orderRemarks]" style="width:420px" maxLength="100" placeholder="给卖家留言"/>');
                return html.join('');
            },
        });

    }

    /**
     * 计算订单金额
     */
    function getOrderMoney() {
        var params = {};
        params.num = num;
        params.orderRemarks = $('#c-orderRemarks').val();
        params.areaId2 = $('#c-category2').val();
        params.isUseScore = 0;
        params.useScore = 0;
        $.ajax({
            url: '/addons/mall/order/getOrderMoney',
            type: 'post',
            dataType: 'json',
            data: params,
            success: function (ret) {
                if (ret.length > 0) {
                    $table.bootstrapTable('load', ret);
                }
            },
        });
    }

    $(function () {
        initTable();

        $('#locale').change(initTable);

        //getOrderMoney();

    })

    /**
     * 选择送货方式
     */
    function changeDeliverType(n, index, obj) {
        changeSelected(n, index, obj);
        if (n == 0) {
            $(".address").show();
        } else {
            $(".address").hide();
        }
        getOrderMoney();
    }


    var invoicebox;

    /**
     *修改开票信息
     */
    function changeInvoice(t, str, obj) {
        var param = {};
        param.invoiceis = $('#c-invoiceis').val();
        param.invoiceId = $('#c-invoiceId').val();
        var loading = layer.load({msg: '正在请求数据，请稍后...'});
        $.post('/addons/mall/invoice/index', param, function (data) {
            layer.close(loading);
            // layer弹出层
            invoicebox = layer.open({
                title: '发票信息',
                type: 1,
                area: ['628px', '420px'], //宽高
                content: data,
                success: function () {
                    if (param.invoiceId > 0) {
                        $('.inv_codebox').show();
                        $('#invoice_num').val($('#invoiceCode_' + param.invoiceId).val());
                    }
                },
            });
        });
    }

    function changeInvoiceItem(t, obj) {
        $(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
        $('.inv_editing').remove();// 删除正在编辑中的发票信息
        $('.inv_add').show();
        $('#c-invoiceId').val(t);
        if (t == 0) {
            // 为个人时，隐藏识别号
            $('.inv_codebox').css({display: 'none'});
            $('#invoice_num').val(' ');
        } else {
            $('#invoice_num').val($('#invoiceCode_' + t).val());
            $('.inv_codebox').css({display: 'block'});
        }
        $("#c-invoice_obj").val(t);
    }

    // 是否需要开发票
    function changeInvoiceItem1(t, obj) {
        $(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
        $('#c-invoiceis').val(t);
    }

    // 显示发票增加
    function invAdd() {
        $("#c-invoiceId").val(0);
        $("#c-invoice_obj").val(1);
        $('#invoice_num').val('');
        $('.inv_li').removeClass('inv_li_curr');// 移除当前选中样式
        $('.inv_ul').append('<li class="inv_li inv_li_curr inv_editing"><input type="text" id="invoiceHead" placeholder="新增单位发票抬头" value="" style="width:65%;height:21px;padding:1px;"><i></i><div style="top:8px;" class="inv_opabox"><a href="javascript:void(0)" onCLick="addInvoice()">保存</a></div></li>');
        $('.inv_ul').scrollTop($('.inv_ul')[0].scrollHeight);// 滚动到底部
        $('.inv_add').hide();// 隐藏新增按钮
        $('.inv_codebox').css({display: 'block'});// 显示`纳税人识别号`
    }

    // 执行发票抬头新增
    function addInvoice() {
        var head = $('#invoiceHead').val();
        if (head.length == 0) {
            layer.msg('发票抬头不能为空');
            return;
        }
        var loading = Load({msg: '正在提交数据，请稍后...'});
        $.post('/addons/mall/Invoice/add', {invoiceHead: head}, function (data) {
            var json = toJson(data);
            layer.close(loading);
            if (json.status == 1) {
                $('#c-invoiceId').val(json.data.id);
                layer.msg(json.msg, {icon: 1});
                $('.inv_editing').remove();
                var code = [];
                code.push('<li class=\'inv_li inv_li_curr\' onClick="changeInvoiceItem(\'' + json.data.id + '\',this)">');
                code.push('<input type="text" value="' + head + '" readonly="readonly" class="invoice_input" id="invoiceHead_' + json.data.id + '" />');
                code.push('<input type="hidden" id="invoiceCode_' + json.data.id + '" value=""} /><i></i>');
                code.push('<div class="inv_opabox">');
                code.push('<a href=\'javascript:void(0)\' onClick="invEdit(\'' + json.data.id + '\',this)" class="edit_btn">编辑</a>');
                code.push('<a href=\'javascript:void(0)\' onClick="editInvoice(\'' + json.data.id + '\',this)" style="display:none;" class="save_btn">保存</a>');
                code.push('<a href=\'javascript:void(0)\' onClick="delInvoice(\'' + json.data.id + '\',this)">删除</a></div></li>');
                $('.inv_li:first').after(code.join(''));
                // 显示新增按钮
                $('.inv_add').show();
            } else {
                layer.msg(json.msg, {icon: 2});
            }
        });
    }

    // 显示发票修改
    function invEdit(id, obj) {
        var input = $(obj).parent().parent().find('.invoice_input');
        input.removeAttr('readonly').focus();
        input.mouseup(function () {
            return false
        });
        $(obj).parent().parent().mouseup(function () {
            input.attr('readonly', 'readonly');
            $(obj).show().siblings('.save_btn').hide();
        });
        $(obj).hide().siblings('.save_btn').show();
        var invoice_code = $('#invoiceCode_' + id).val();
        $('.inv_codebox').css({display: 'block'})
        $('#invoice_num').val(invoice_code);// 显示`纳税人识别号`)
    }

    // 完成发票修改
    function editInvoice(id, obj) {
        var head = $('#invoiceHead_' + id).val();
        if (head.length == 0) {
            layer.msg('发票抬头不能为空');
            return;
        }
        var loading = Load({msg: '正在提交数据，请稍后...'});
        $.post('/addons/mall/Invoice/edit', {invoiceHead: head, id: id}, function (data) {
            var json = toJson(data);
            layer.close(loading);
            if (json.status == 1) {
                var input = $(obj).parent().parent().find('.invoice_input');
                input.attr('readonly', 'readonly')
                $(obj).hide().siblings('.edit_btn').show();
                layer.msg(json.msg, {icon: 1});
            } else {
                layer.msg(json.msg, {icon: 2});
            }
        });
    }

    // 设置页面显示值
    function setInvoiceText(invoiceHead) {
        var invoiceis = $('#c-invoiceis').val();
        var invoiceObj = $('#c-invoice_obj').val();// 发票对象
        var text = '不开发票';
        if (invoiceis == 1) {
            text = (invoiceObj == 0) ? '普通发票（纸质）  个人   明细' : '普通发票（纸质）' + invoiceHead + ' 明细';
        }
        $('#invoice_info').html(text);
        layer.close(invoicebox);

    }

    /**
     *保存纳税人识别号
     */
    function saveInvoice() {
        var invoiceis = $('#c-invoiceis').val();
        var num = $('#invoice_num').val();
        var id = $('#c-invoiceId').val();
        var invoiceHead = $('#invoiceHead').val();// 发票抬头
        var url = '/addons/mall/Invoice/add';
        var params = {};
        if (id > 0) {
            url = '/addons/mall/Invoice/edit';
            invoiceHead = $('#invoiceHead_' + id).val();// 发票抬头
            params.id = id;
        }
        params.invoiceHead = invoiceHead;
        params.invoiceCode = num;
        if ($('#c-invoice_obj').val() != 0) {
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: {"row": params},
                success: function (ret) {
                    if (ret.code) {
                        // 判断用户是否需要发票
                        setInvoiceText(invoiceHead);
                        if (id == 0) $('#c-invoiceId').val(ret.data.id)
                    } else {
                        if (ret.msg) Toastr.error(ret.msg);
                    }
                },
            });

        } else {
            setInvoiceText('');
        }
    }

    // 删除发票信息
    function delInvoice(id, obj) {
        confirm({
            content: '您确定要删除该发票信息吗？', yes: function (index) {
                $.post('/addons/mall/invoice/del', {ids: id}, function (data, textStatus) {
                    var json = toJson(data);
                    if (json.status == 1) {
                        layer.msg(json.msg, {icon: 1});
                        $(obj).parent().parent().remove();
                        $('#c-invoiceId').val(0);
                        // 选中 `个人`
                        $('.inv_li:first').click();
                    } else {
                        layer.msg(json.msg, {icon: 2});
                    }
                });
            }
        });
    }

    /**
     * 提交订单
     */
    function addOrder(){
        var form = $("#add-form");
        $.ajax({
            url: form.attr("action"),
            data: form.serialize(),
            type: 'post',
            dataType: 'json',
            success: function (ret) {
                if(ret.code){
                    if(ret.msg) Toastr.success(ret.msg);
                    location.href = ret.url;
                }else{
                    if(ret.msg) Toastr.error(ret.msg);
                }
            },
        });
    }

</script>
{__block__}
{/block}

